package org.androidpn.server.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.OrderBy;
import javax.persistence.Transient;

import org.androidpn.server.util.XMLUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * Entity baseEntity
 * 
 * @author 蔡琪
 * 
 */
@MappedSuperclass
public class BaseEntity implements Serializable {

	private static final long serialVersionUID = -4996704732881725466L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@OrderBy(value = "desc")
	private Long id;

	@Column(name = "create_date", updatable = false)
	@OrderBy(value = "desc")
	private Date createDate = new Date();

	@Column(name = "modify_date")
	private Date modifyDate = new Date();

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public Date getModifyDate() {
		return modifyDate;
	}

	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}

	/**
	 * 从xml字符串中解析出基本实体对象的属性
	 * 
	 * @param <T>
	 * 
	 * @param xml
	 *            xml字符串
	 * @return Role对象
	 */
	@Transient
	protected static <T extends BaseEntity> T fromXML(String xml, Class<T> clasz) {
		T entity = null;
		Document doc;
		try {
			entity = clasz.newInstance();
			doc = DocumentHelper.parseText(xml);
			Element element = doc.getRootElement();
			String id = element.elementText("id");
			String createDate = element.elementText("createDate");
			String modifyDate = element.elementText("modifyDate");
			entity.setId(XMLUtils.getLongFromStr(id));
			entity.setCreateDate(new Date(XMLUtils.getLongFromStr(createDate)));
			entity.setModifyDate(new Date(XMLUtils.getLongFromStr(modifyDate)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}

	/**
	 * 将当前对象转化为xml字符串
	 * 
	 * @return
	 */
	@Transient
	public String toXML() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(XMLUtils.createSingleNode("id", this.getId()));
		buffer.append(XMLUtils.createSingleNode("createDate",
				createDate.getTime()));
		buffer.append(XMLUtils.createSingleNode("modifyDate",
				modifyDate.getTime()));
		return buffer.toString();
	}
}
